package com.meisupic.copyright.service.impl;

import static com.meisupic.copyright.common.Constants.CERTIFICATES_DIR;
import static com.meisupic.copyright.common.Constants.COMMITMENT;
import static com.meisupic.copyright.common.Constants.OSS_HOST;
import static com.meisupic.copyright.common.Constants.RIGHT_OWN_MODE_LEGAL_WORKS;
import static com.meisupic.copyright.common.Constants.WORKS_DIR;

import com.meisupic.copyright.common.AuthProcessEnum;
import com.meisupic.copyright.common.AuthorizeRuleEnum;
import com.meisupic.copyright.common.Constants;
import com.meisupic.copyright.common.WorksProcessDetailEnum;
import com.meisupic.copyright.common.WorksProcessEnum;
import com.meisupic.copyright.domain.po.CopyRightWorks;
import com.meisupic.copyright.domain.po.RealNameAuth;
import com.meisupic.copyright.domain.vo.CopyrightWorksApiVo;
import com.meisupic.copyright.domain.vo.CopyrightWorksResultApiVo;
import com.meisupic.copyright.domain.vo.RealnameAuthApiVo;
import com.meisupic.copyright.exception.BizException;
import com.meisupic.copyright.repo.CopyRightWorksRepo;
import com.meisupic.copyright.service.ApiService;
import com.meisupic.copyright.service.IDeclarationFilesService;
import com.meisupic.copyright.service.IOssService;
import com.meisupic.copyright.service.IRealNameAuthService;
import com.meisupic.copyright.util.BeanMapper;
import com.meisupic.copyright.util.BeanUtil;
import com.meisupic.copyright.util.StringUtil;
import java.math.BigDecimal;
import java.net.URL;
import java.util.concurrent.CompletableFuture;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class ApiServiceImpl implements ApiService {

  @Autowired
  IOssService ossService;

  @Autowired
  IRealNameAuthService realNameAuthService;

  @Autowired
  private IDeclarationFilesService declarationFilesService;

  @Autowired
  CopyRightWorksRepo copyRightWorksRepo;

  private String DECLARATION_FILE_PATH = OSS_HOST + Constants.DECLARATION_FILE_PATH;

  private Logger logger = LoggerFactory.getLogger(this.getClass());

  @Override
  public void saveRealNameAuth(RealnameAuthApiVo realnameAuthApiVo) {
    //处理图片
    String documentImgPositiveUrl = realnameAuthApiVo.getDocumentImgPositiveUrl();
    String documentImgPositiveKey = CERTIFICATES_DIR + StringUtil.get32UUID();
    String documentImgBackUrl = realnameAuthApiVo.getDocumentImgBackUrl();
    String documentImgBackKey = CERTIFICATES_DIR + StringUtil.get32UUID();

    String corporateIdentityCardImgPositiveUrl = realnameAuthApiVo
        .getCorporateIdentityCardImgPositiveUrl();
    String corporateIdentityCardImgPositiveKey = CERTIFICATES_DIR + StringUtil.get32UUID();
    String corporateIdentityCardImgBackUrl = realnameAuthApiVo.getCorporateIdentityCardImgBackUrl();
    String corporateIdentityCardImgBackKey = CERTIFICATES_DIR + StringUtil.get32UUID();

    RealNameAuth realNameAuth = BeanMapper.map(realnameAuthApiVo, RealNameAuth.class);
    realNameAuth.setDocumentImgPositive(OSS_HOST + documentImgPositiveKey);
    if (StringUtils.isNotEmpty(documentImgBackUrl)) {
      realNameAuth.setDocumentImgBack(OSS_HOST + documentImgBackKey);
    }
    if (StringUtils.isNotEmpty(corporateIdentityCardImgPositiveUrl)) {
      realNameAuth
          .setCorporateIdentityCardImgPositive(OSS_HOST + corporateIdentityCardImgPositiveKey);
    }
    if (StringUtils.isNotEmpty(corporateIdentityCardImgBackUrl)) {
      realNameAuth.setCorporateIdentityCardImgBack(OSS_HOST + corporateIdentityCardImgBackKey);
    }
    realNameAuthService.saveApiRealNameAuth(realNameAuth);
    Long id = realNameAuth.getId();
    realnameAuthApiVo.setId(id);
    CompletableFuture.runAsync(() -> {
      try {
        ossService.putObject(documentImgPositiveKey,
            IOUtils.toByteArray(new URL(documentImgPositiveUrl)));
        if (StringUtils.isNotEmpty(documentImgBackUrl)) {
          ossService
              .putObject(documentImgBackKey, IOUtils.toByteArray(new URL(documentImgBackUrl)));
        }
        if (StringUtils.isNotEmpty(corporateIdentityCardImgPositiveUrl)) {
          ossService.putObject(corporateIdentityCardImgPositiveKey,
              IOUtils.toByteArray(new URL(corporateIdentityCardImgPositiveUrl)));
        }
        if (StringUtils.isNotEmpty(corporateIdentityCardImgBackUrl)) {
          ossService.putObject(corporateIdentityCardImgBackKey,
              IOUtils.toByteArray(new URL(corporateIdentityCardImgBackUrl)));
        }
      } catch (Exception e) {
        logger.error("上传图片到oss失败，异常信息：{}", e.getMessage());
        RealNameAuth updateEntity = realNameAuthService.findById(id);
        updateEntity.setAuditStatus(AuthProcessEnum.refused);
        realNameAuthService.updateRealNameAuth(updateEntity);
        //todo 回调客户端

      }
    });


  }

  /**
   * 保存作品登记数据
   */
  @Override
  public void saveCopyrightWorks(CopyrightWorksApiVo copyrightWorksApiVo) {
    //验证实名认证用户
    Long applicantId = copyrightWorksApiVo.getApplicantId();
    RealNameAuth realNameAuth = realNameAuthService.findById(applicantId);
    if (StringUtil.isEmpty(realNameAuth)) {
      throw new BizException("未找到申请人实名认证信息");
    }
    String statementSuffix = StringUtil.get32UUID();
    String image_key = WORKS_DIR + "/" + StringUtil.get32UUID();
    CopyRightWorks copyRightWorks = BeanMapper.map(copyrightWorksApiVo, CopyRightWorks.class);
    copyRightWorks.setSeriesOfWorks(false);
    copyRightWorks.setCommitment(COMMITMENT);
    copyRightWorks.setCreatorId(realNameAuth.getCreatorId());
    copyRightWorks.setCreateor(realNameAuth.getAuthName());
    copyRightWorks.setApplicantAccountId(realNameAuth.getAccountId());
    copyRightWorks.setOriginalStatement(statementSuffix + "_1.pdf");
    copyRightWorks.setCreativeStatement(statementSuffix + "_2.pdf");
    if (copyRightWorks.getRightOwnMode() == RIGHT_OWN_MODE_LEGAL_WORKS) {
      copyRightWorks.setLegalCreationStatement(statementSuffix + "_3.pdf");
    }
    copyRightWorks.setWorksProcess(WorksProcessEnum.commited);
    copyRightWorks.setWorksProcessDetail(WorksProcessDetailEnum.commited);
    declarationFilesService.generateFiles(copyRightWorks, "");

    //声明文件重新赋值完整路径
    copyRightWorks
        .setOriginalStatement(DECLARATION_FILE_PATH + copyRightWorks.getOriginalStatement());
    copyRightWorks
        .setCreativeStatement(DECLARATION_FILE_PATH + copyRightWorks.getCreativeStatement());

    if (copyRightWorks.getRightOwnMode() == RIGHT_OWN_MODE_LEGAL_WORKS) {
      copyRightWorks.setLegalCreationStatement(DECLARATION_FILE_PATH + statementSuffix + "_3.pdf");
    }
    copyRightWorks.setImageName(OSS_HOST + image_key);
    copyRightWorks.setCategoryId(0);
    copyRightWorks.setKeywords("");
    copyRightWorks.setAuthorizeRule(AuthorizeRuleEnum.CustomAuthorize);
    copyRightWorks.setSplitPercentage(BigDecimal.ONE);
    copyRightWorks.setIsOnSale(0);
    if (copyRightWorks.getId() != null) {
      CopyRightWorks copyRightWorksExistEnity = copyRightWorksRepo
          .findOne(copyRightWorks.getId());
      if (WorksProcessEnum.commited.name()
          .equals(copyRightWorksExistEnity.getWorksProcess().name())) {
        logger.info("修改审核中的作品id{}", copyRightWorksExistEnity.getId());
        throw new BizException("审核中状态下不允许修改");
      } else if (WorksProcessEnum.passed.name()
          .equals(copyRightWorksExistEnity.getWorksProcess().name())) {
        logger.info("修改通过的作品id{}", copyRightWorksExistEnity.getId());
        throw new BizException("已通过的作品不允许修改");
      }
      BeanUtil.copyPropertiesIgnoreNull(copyRightWorks, copyRightWorksExistEnity);
      copyRightWorksRepo.save(copyRightWorksExistEnity);
    } else {
      copyRightWorksRepo.save(copyRightWorks);
      copyrightWorksApiVo.setId(copyRightWorks.getId());
    }

    CompletableFuture.runAsync(() -> {
      try {
        ossService.putObject(image_key,
            IOUtils.toByteArray(new URL(copyrightWorksApiVo.getWorksImageUrl())));
      } catch (Exception e) {
        logger.error("api获取客户端图片失败，失败原因：{}", e.getMessage());

      }
    });
  }

  @Override
  public CopyrightWorksResultApiVo queryCopyrightWorksById(Long id) {
    CopyRightWorks copyRightWorks = copyRightWorksRepo.findOne(id);
    if (copyRightWorks != null) {
      Long creatorId = copyRightWorks.getCreatorId();
      RealNameAuth realNameAuth = realNameAuthService.findByUserId(creatorId);
      String clientId = realNameAuth.getClientId();
      String principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal()
          .toString();
      if (principal.equals(clientId)) {
        CopyrightWorksResultApiVo resultApiVo = BeanMapper
            .map(copyRightWorks, CopyrightWorksResultApiVo.class);
        return resultApiVo;
      }
    }
    return null;
  }
}
